<template>
    <div class="notice-list">
        <common-list @resert="resert" ref="commonListRef">
            <template #operate="{ scope }">
                <el-button v-if="store.btns.find((item) => item.name === '详情')" link type="primary" size="small"
                    @click="toPolicyTemplate(scope)">详情</el-button>
                <div v-if="store.btns.find((item) => item.name === '详情')" class="line" />
                <el-button v-if="store.btns.find((item) => item.name === '重命名')" link type="primary" size="small"
                    @click="add(scope)">重命名</el-button>
                <div v-if="store.btns.find((item) => item.name === '重命名')" class="line" />
                <el-button v-if="store.btns.find((item) => item.name === '删除')" link type="primary" size="small"
                    @click="deletes(scope)">删除</el-button>
                <div v-if="store.btns.find((item) => item.name === '删除') && store.btns.find((item) => item.name === '关联设备')"
                    class="line" />
                <el-button v-if="store.btns.find((item) => item.name === '关联设备')" link type="primary" size="small"
                    @click="openDialogVisible(scope)">关联设备</el-button>
            </template>
            <template #state="{ scope }">
                <el-switch v-model="scope.scope.row.state" :active-value="1" :inactive-value="0" inline-prompt
                    active-text="启用" inactive-text="禁用" @change="change(scope.scope.row)" />
            </template>
            <template #isTemplate="{ scope }">
                <el-switch v-model="scope.scope.row.isTemplate" inline-prompt active-text="开启" inactive-text="关闭"
                    @change="changes(scope.scope.row)" />
            </template>
            <template #btns>
                <div class="btns">
                    <el-button type="primary" @click="add(null)"
                        v-if="store.btns.find((item) => item.name === '新增策略')">新增策略</el-button>
                    <w-button @click="allDeletes" v-if="store.btns.find((item) => item.name === '批量删除')">批量删除</w-button>
                    <w-button @click="toCheckItemTemplateLibrary"
                        v-if="store.btns.find((item) => item.name === '检查项库')">检查项库</w-button>
                </div>
            </template>
        </common-list>
        <el-dialog destroy-on-close v-model="dialogVisible" title="关联设备" :close-on-click-modal="false" width="30%">
            <el-form :model="equipmentForm" label-width="80px" :rules="equipmentRules" ref="equipmentRuleFormRef"
                :disabled="disabled">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="设备类型">
                            <el-select v-model="equipmentForm.equipmentType" placeholder="请选择设备类型" @change="typeChange">
                                <el-option v-for="item in typeOption" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="区域位置">
                            <el-select v-model="equipmentForm.areaLocation" placeholder="请选择区域位置" @change="locationChange">
                                <el-option v-for="item in locationOption" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="关联设备" prop="equipmentId">
                            <el-select v-model="equipmentForm.equipmentId" placeholder="请选择关联设备">
                                <el-option v-for="item in equipmentOption" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="button">
                    <div class="submit" @click="openDint">
                        <text class="submitText">提交</text>
                    </div>
                    <div class="close" @click="closeDialogVisible">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog destroy-on-close v-model="dint" title="" :close-on-click-modal="false" width="40%" :show-close="false">
            <div class="dint">
                <el-icon color="#FF4D4F" size="22">
                    <WarningFilled />
                </el-icon><text class="dint-text">更改设备的关联策略，次日起的所有计划重置，是否继续？</text>
            </div>
            <div class="button">
                <div class="submit" @click="dintSubmit">
                    <text class="submitText">提交</text>
                </div>
                <div class="close" @click="closeDint">
                    <text class="closeText">取消</text>
                </div>
            </div>
        </el-dialog>
        <el-dialog destroy-on-close v-model="dialogVisibles" :title="title" :close-on-click-modal="false" width="30%">
            <el-form :model="form" hide-required-asterisk ref="ruleFormRef">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="策略名称" prop="name" :rules="[
                            {
                                required: true,
                                message: '策略名称是必填的',
                                trigger: 'change'
                            }
                        ]">
                            <el-input maxlength="30" v-model="form.name" placeholder="请输入策略名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :class="{ none: title == '重命名' }" :span="24" class="flex">
                        <el-form-item label-width="0">
                            <el-radio-group v-model="radio" style="padding-right: 12px">
                                <el-radio :label="true" @click.native.prevent="templateClick(true)">使用已有策略模版</el-radio>
                            </el-radio-group>
                            <el-select v-model="form.templateId" placeholder="请选择策略模版" @change="templateChange">
                                <el-option v-for="item in templateOption" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="button">
                    <div v-if="title != '重命名'" class="submit" @click="submit">
                        <text class="submitText">下一步</text>
                    </div>
                    <div v-else class="submit" @click="rename">
                        <text class="submitText">确认</text>
                    </div>
                    <div class="close" @click="closeDialogVisibles">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { provide, reactive, ref } from "vue";
import { tableConfig, formConfig, equipmentRules } from "./config";
import {
    addstrategy,
    getinspectionitemtemplatelist,
    getstrategypage,
    editstrategylinkequipment,
    updateistemplateasync,
    updatestateasync,
    getstrategy,
    batchdeletestrategy,
    getstategytemplatelist,
    editstrategyname
} from "@/service/api/tacticalManagement.js";
import { getequipmenttypelist, getequipmentarealocationlist, getrelationequipmentlist } from "@/service/api/equipmentManagement.js";
import { mainStore } from "@/store/main.js";
import { useRouter } from "vue-router";
import wButton from "@/components/wButton.vue";
import { WarningFilled } from "@element-plus/icons-vue";

const store = mainStore();
const loading = ref(false);
const router = useRouter();
const commonListRef = ref(null);
const dialogVisible = ref(false);
const dialogVisibles = ref(false);
const formData = reactive({ name: "", state: "" });
const locationOption = ref([]);
const typeOption = ref([]);
const equipmentOption = ref([]);
const equipment = ref({
    type: "",
    location: ""
});
const dint = ref(false);
const equipmentForm = ref({
    strategyId: "",
    equipmentId: "",
    equipmentType: "",
    areaLocation: ""
});
const equipmentRuleFormRef = ref(null);
const radio = ref(false);
const templateOption = ref([]);
const form = ref();
const ruleFormRef = ref(null);
const firstChange = ref(false);
const title = ref();

getequipmenttypelist().then((res) => {
    if (res.code === 200) {
        typeOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
    }
});
getequipmentarealocationlist().then((res) => {
    if (res.code === 200) {
        locationOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
    }
});

const typeChange = (value) => {
    equipment.value.type = value;
    equipmentForm.value.equipmentId = "";
    getrelationequipmentlist(equipment.value).then((res) => {
        if (res.code === 200) {
            equipmentOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
        }
    });
};
const locationChange = (value) => {
    equipment.value.location = value;
    equipmentForm.value.equipmentId = "";
    getrelationequipmentlist(equipment.value).then((res) => {
        if (res.code === 200) {
            equipmentOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
        }
    });
};
const templateChange = (value) => {
    form.value.TemplateName = templateOption.value.filter((item) => {
        return item.value == value;
    })[0].label;
};
const add = (scope) => {
    if (scope == null) {
        radio.value = false;
        templateOption.value = []
        form.value = {
            templateId: "",
            name: "",
            templateName: ""
        };
        title.value = "新增策略";
    } else {
        form.value = {
            id: scope.scope.row.id,
            name: scope.scope.row.name
        };
        title.value = "重命名";
    }
    dialogVisibles.value = true;
};
const resert = () => {
    Object.keys(formData).forEach((key) => (formData[key] = ""));
};
const templateClick = (value) => {
    radio.value = radio.value == value ? !value : value;
    if (radio.value) {
        getstategytemplatelist().then((res) => {
            if (res.code === 200) {
                templateOption.value = res.data.map((item) => ({ label: item.name, value: item.id }));
            }
        });
    } else {
        form.value.templateId = "";
        form.value.templateName = "";
        templateOption.value = [];
    }
};
const toCheckItemTemplateLibrary = () => {
    router.push("/main/tacticalManagement/checkItemTemplateLibrary");
};
const toPolicyTemplate = (scope) => {
    router.push("/main/tacticalManagement/policyTemplate?id=" + scope.scope.row.id + "&name=" + scope.scope.row.name);
};

const openDialogVisible = (scope) => {
    getrelationequipmentlist(equipment.value).then((res) => {
        if (res.code === 200) {
            equipmentOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
        }
    });
    equipment.value = {
        type: "",
        location: ""
    };
    getrelationequipmentlist(equipment.value).then((res) => {
        if (res.code === 200) {
            equipmentOption.value = res.data.map((item) => ({ label: item.name, value: item.value }));
        }
    });
    equipmentForm.value = {
        strategyId: scope.scope.row.id,
        equipmentId: "",
        equipmentType: "",
        areaLocation: ""
    };
    dialogVisible.value = true;
};
const closeDialogVisible = () => {
    dialogVisible.value = false;
};
const closeDialogVisibles = () => {
    dialogVisibles.value = false;
};
const submit = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            const loadingInstance = ElLoading.service();
            addstrategy(form.value)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            message: "添加成功",
                            type: "success"
                        });
                        router.push("/main/tacticalManagement/policyTemplate?id=" + res.data.id + "&templateName=" + form.value.templateName + "&name=" + form.value.name);
                    }
                    loadingInstance.close();
                })
                .catch(() => {
                    loadingInstance.close();
                });
        }
    });
};
const rename = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            const loadingInstance = ElLoading.service();
            editstrategyname(form.value)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            message: "重命名成功",
                            type: "success"
                        });
                    }
                    commonListRef.value.tableRef.getTableList();
                    loadingInstance.close();
                    dialogVisibles.value = false;
                })
                .catch(() => {
                    loadingInstance.close();
                });
        }
    });
};
const openDint = () => {
    if (!equipmentRuleFormRef.value) return;
    equipmentRuleFormRef.value.validate((valid) => {
        if (valid) {
            dialogVisible.value = false;
            dint.value = true;
        }
    });
};
const closeDint = () => {
    dint.value = false;
};
const dintSubmit = () => {
    const loadingInstance = ElLoading.service();
    editstrategylinkequipment({
        strategyId: equipmentForm.value.strategyId,
        equipmentId: equipmentForm.value.equipmentId
    })
        .then((res) => {
            if (res.code === 200) {
                ElMessage({
                    message: "修改成功",
                    type: "success"
                });
            }
            dint.value = false;
            commonListRef.value.tableRef.getTableList();
            loadingInstance.close();
        })
        .catch(() => {
            loadingInstance.close();
        });
};
const close = () => {
    dialogVisible.value = false;
};
const change = (data) => {
    if (!firstChange.value) {
        firstChange.value = true;
        return;
    } else {
        editstrategyname({ id: data.id, state: data.state })
            .then((res) => {
                commonListRef.value.tableRef.getTableList();

            })
            .catch(() => {
                commonListRef.value.tableRef.getTableList();
            });
    }
};
const changes = (data) => {

    editstrategyname({ id: data.id, isTemplate: data.isTemplate ? 1 : 0 })
        .then((res) => {
            commonListRef.value.tableRef.getTableList();

        })
        .catch(() => {
            commonListRef.value.tableRef.getTableList();
        });
};
const allDeletes = () => {
    const choose = commonListRef.value.tableRef.allSelectTable.flat().map((item) => item.id);
    if (choose.length == 0) {
        ElMessage({
            message: "请选中需要删除的数据再进行批量删除",
            type: "warning"
        });
        return;
    }
    ElMessageBox.confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: ""
    }).then(() => {
        const loadingInstance = ElLoading.service();
        batchdeletestrategy({
            ids: choose
        })
            .then((res) => {
                if (res.code === 200) {
                    ElMessage({
                        type: "success",
                        message: "删除成功"
                    });
                }

                commonListRef.value.tableRef.getTableList();
                loadingInstance.close();
            })
            .catch(() => {
                loadingInstance.close();
            });
    });
};
const deletes = (scope) => {
    ElMessageBox.confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: ""
    }).then(() => {
        const loadingInstance = ElLoading.service();
        batchdeletestrategy({
            ids: [scope.scope.row.id]
        })
            .then((res) => {
                if (res.code === 200) {
                    ElMessage({
                        type: "success",
                        message: "删除成功"
                    });
                    commonListRef.value.tableRef.allSelectTable = [];
                }
                commonListRef.value.tableRef.getTableList();
                loadingInstance.close();
            })
            .catch(() => {
                loadingInstance.close();
            });
    });
};
provide("formData", formData);
provide("formConfig", formConfig);
provide("tableConfig", tableConfig);
provide("apiFn", getstrategypage);
// provide("requestBody", "query");
provide("title", "策略明细");
</script>

<style lang="less" scoped>
::v-deep(.el-dialog__title) {
    color: #1b3646;
    font-weight: 600;
}

::v-deep(.el-form-item__label) {
    color: #1b3646;
}

::v-deep(.el-radio__label) {
    color: #1b3646;
    font-weight: 600;
}

.dint {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 24px;
}

.dint-text {
    font-size: 16px;
    font-weight: 600;
    color: #1b3646;
}

.flex {
    display: flex;
}

.notice-list {
    height: 100%;

    .line {
        display: inline-block;
        margin: 0 13px;
        width: 1px;
        height: 8px;
        border: 1px solid #dcdcdc;
    }

    .btns {
        display: flex;

        .resert {
            border: 1px solid @main-color;
            color: @main-color;
        }
    }
}

.button {
    display: flex;
    justify-content: center;
}

.close {
    margin-left: 8px;
    width: 78px;
    height: 30px;
    border: 1px solid #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.closeText {
    color: #00428e;
    font-size: 14px;
    font-weight: 400;
}

.submit {
    width: 80px;
    height: 32px;
    background: #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.submitText {
    color: #ffffff;
    font-size: 14px;
    font-weight: 400;
}
</style>
<style>
.none {
    display: none !important;
}

.el-message-box__btns {
    justify-content: center;
}

.el-message-box__title {
    font-weight: 600;
    color: #1b3646;
}

.el-message-box__message {
    color: #1b3646;
}

.el-message-box__btns .el-button--primary {
    background-color: #00428e;
}
</style>
